<template>
	<tm-app ref="app">
		<tm-navbar title="家长注册" color="orange" linear="right" beforeBack="true" hideHome="true"></tm-navbar>




		<tm-form v-if="showflag" @submit="confirm" v-model="entity" ref="form" :label-width="190">
			<!--<tm-divider align="left" label="身份证图片(带身份号码面)"></tm-divider>
			<tm-upload color="orange" :onStart="onZmStart" :imageHeight="200" :rows="1"
				v-model="zmlist" showSort :fileType="['camera']" :default-value="zmlist" ref="up"
				:onSuccessAfter="zmtest" :width="636" maxFile="1" :show-status="false"
				url="https://www.zhaobangyang.cn/wx/bs/upload">
				<template v-slot:icon>
					<tm-text color="orange" label="身份证(带身份号码面)"></tm-text>
				</template>
			</tm-upload>
			<tm-divider align="left" label="身份证图片(带国徽面)"></tm-divider>
			<tm-upload color="orange" :onStart="onStart" :imageHeight="200" :rows="1" v-model="list" :fileType="['camera']" showSort
				:default-value="list" ref="up" :onSuccessAfter="test" :width="636" maxFile="1" :show-status="false"
				url="https://www.zhaobangyang.cn/wx/bs/upload">
				<template v-slot:icon>
					<tm-text color="orange" label="身份证(带国徽面)"></tm-text>
				</template>
			</tm-upload>-->
			<!-- <tm-divider align="left" label="基本信息"></tm-divider> -->
			<!--<tm-input v-model="entity.name" required prefixLabel="姓名:" :margin="[0,10]"
				focusColor="orange"></tm-input>
			<tm-input v-model="entity.cardno" required prefixLabel="身份证号:" :margin="[0,10]"
				focusColor="orange"></tm-input>
			<tm-input v-model="entity.stuname" required prefixLabel="学生姓名:" :margin="[0,10]"
				focusColor="orange"></tm-input>
			<tm-divider align="left" label="位置"></tm-divider>
			<tm-cell @click="showdateq = true" title="选择区域:" :right-text="entity.addr || '请选择'"
				focusColor="orange"></tm-cell>
			<tm-picker v-model:show="showdateq" :columns="citydate3" v-model="entity.addr"
				v-model:model-str="entity.addr"></tm-picker>-->
			<!--<tm-input v-model="entity.addr" required prefixLabel="区域:" :margin="[0,10]"
				focusColor="orange"></tm-input> -->
			<!--
			<tm-input v-model="entity.addrDetail" required prefixLabel="详细地址:" :margin="[0,10]"
				focusColor="orange"></tm-input>
			<tm-input v-model.lazy="entity.phone" required prefixLabel="联系方式:" :margin="[0,10]"
				focusColor="orange"></tm-input>
			<tm-input v-model="entity.code" required @search="sendMessage()" prefixLabel="验证码:" focusColor="orange"
				:margin="[0,10]" searchLabel="获取"></tm-input>-->

			<tm-form-item required label="姓名" labelWidth="0">
				<tm-input :inputPadding="[0, 0]" v-model="entity.name" :transprent="true" :showBottomBotder="false"
					placeholder="请输入姓名"></tm-input>
			</tm-form-item>
			<tm-form-item required label="证件号码" labelWidth="0">
				<tm-input :inputPadding="[0, 0]" v-model="entity.cardno" :transprent="true" :showBottomBotder="false"
					placeholder="请输入证件号码"></tm-input>
			</tm-form-item>
			<tm-form-item required label="选择区域" labelWidth="0">
				<tm-cell @click="showdateq = true" :right-text="entity.addr || '请选择区域'" focusColor="orange"></tm-cell>
				<tm-picker v-model:show="showdateq" :columns="citydate3" v-model="entity.addr"
					v-model:model-str="entity.addr"></tm-picker>
			</tm-form-item>
			<tm-form-item required label="详细地址" labelWidth="0">
				<tm-input :inputPadding="[0, 0]" v-model="entity.addrDetail" :transprent="true"
					:showBottomBotder="false" placeholder="请输入详细地址"></tm-input>
			</tm-form-item>
			<tm-form-item required label="联系方式" labelWidth="0">
				<tm-input :inputPadding="[0, 0]" v-model="entity.phone" :transprent="true" :showBottomBotder="false"
					placeholder="请输入联系方式" @search="sendMessage()" focusColor="orange" :searchLabel="selab"></tm-input>
			</tm-form-item>
			<tm-form-item required label="验证码" labelWidth="0">
				<tm-input :inputPadding="[0, 0]" v-model="entity.code" :transprent="true" :showBottomBotder="false"
					placeholder="请输入验证码"></tm-input>
			</tm-form-item>
			<tm-form-item :border="false">
				<view class=" flex flex-row">
					<view class="flex-1 mr-32">
						<tm-button form-type="submit" color="orange" label="提 交" followTheme="true" block></tm-button>
					</view>
				</view>
			</tm-form-item>

			<tm-form-item :border="false">
				<view class=" flex flex-row">
					<tm-checkbox @change="allChange" color="orange"></tm-checkbox>
					<tm-text color="blue" label="请认真阅读并了解注意事项，并同意《用户服务协议》及《隐私政策》" @click="loadXyContent()"></tm-text>
				</view>
			</tm-form-item>
		</tm-form>

		<tm-message ref="msg" :lines="5"></tm-message>
	</tm-app>
</template>

<script lang="ts" setup>
	import { ref, nextTick } from "vue";
	import { onLoad } from "@dcloudio/uni-app";
	import { isPhone, isEmpty, isIdCard } from "@/tmui/tool/function/util";
	import tmMessage from "@/tmui/components/tm-message/tm-message.vue";
	import { getcode, savejs, saveJzZmSfz, saveJzFmSfz, getOcrDetail } from '@/api/jz'
	import { getDetailBywxid } from '@/api/jzdetail'

	const msg = ref<InstanceType<typeof tmMessage> | null>(null)
	const placement = ref('top')
	const userid = ref('');
	const showflag = ref(true);
	const dateStr2 = ref('');
	const showdateq = ref(false);
	const pickydata2 = ref([]);
	const xyflag = ref(false);
	const list = ref([]);
	const zmlist = ref([]);
	const imgbase = ref("");
	const selab = ref("获取验证码");
	const citydate3 = ref([
		{ text: "东港区", id: 0, children: [{ text: "日照街道", id: 100 }, { text: "秦楼街道", id: 101 }, { text: "石臼街道", id: 102 }] }, { text: "经开区", id: 2, children: [{ text: "北京路街道", id: 200 }, { text: "奎山街道", id: 201 }] }, { text: "山海天", id: 3, children: [{ text: "卧龙山街道", id: 300 }, { text: "两城街道", id: 301 }] }, { text: "高新区", id: 4, children: [{ text: "香河街道", id: 400 }] },
	]);
	const zmSfzImgSrc = ref("");
	const fmSfzImgSrc = ref("");
	// const remainingTime = ref(0);
	const msgFlag = ref(false);


	const entity = ref({
		name: "",
		cardno: "",
		stuname: "",
		addr: "",
		phone: "",
		code: "",
		wxid: "",
		addrDetail: "",
		zmsfz: "",
		fmsfz: "",
		sfzDetail: ""
	})

	const zmtest = (item : any) => {
		let d = item.response;
		let isOk = true
		try {
			let p = JSON.parse(d)
			if (p?.code !== 0) {
				isOk = false;
			}
		} catch (e) {
			isOk = false;
		}

		return isOk;
	}

	/**
	 * 以下是测试上传后。如果服务返回 的不是json对象数据就让其失败。
	 */
	const test = (item : any) => {
		let d = item.response;
		let isOk = true
		try {
			let p = JSON.parse(d)
			if (p?.code !== 0) {
				isOk = false;
			}
		} catch (e) {
			isOk = false;
		}

		return isOk;
	}
	const onZmStart = (item : any) => {
		// console.log('图片信息:',item)
		// console.log('图片信息:', item.url)
		imgToBase64(item.url);
		return true;
	}

	// 图片转base64方法
	const imgToBase64 = async (url : string) => {
		// #ifdef MP-WEIXIN
		uni.getFileSystemManager().readFile({
			filePath: url, // 选择图片返回的相对路径
			encoding: 'base64', // 编码格式
			success: res => { // 成功的回调
				// console.log(res, '返回结果');
				imgbase.value = `data:image/jpeg;base64,${res.data}`;
				// 进行保存上传图片
				saveZmSfz();
			},
			fail: (e) => {
				console.log("图片转换失败");
			}
		})
		// #endif
	}
	// 身份证正面保存
	const saveZmSfz = async () => {
		let param = { "base": imgbase.value, "wxid": userid.value };
		const result = await saveJzZmSfz(param);
		console.log(JSON.stringify(result));
		zmSfzImgSrc.value = result.url;
		entity.value.zmsfz = result.url;
		// 通过上传的身份证图片，识别身份证信息
		loadOcrDetail();
	}
	// 身份证反面保存
	const saveFmSfz = async () => {
		let param = { "base": imgbase.value, "wxid": userid.value };
		const result = await saveJzFmSfz(param);
		fmSfzImgSrc.value = result.url;
		entity.value.fmsfz = result.url;
	}

	const loadOcrDetail = async () => {
		let param = { "url": entity.value.zmsfz };
		console.log(JSON.stringify(param));
		const result = await getOcrDetail(param);
		console.log(JSON.stringify(result));
		entity.value.cardno = result.msg.id;
		entity.value.name = result.msg.name;
	}

	const onStart = (item : any) => {
		imgFmToBase64(item.url);
		return true;
	}

	// 图片转base64方法
	const imgFmToBase64 = async (url : string) => {
		// #ifdef MP-WEIXIN
		uni.getFileSystemManager().readFile({
			filePath: url, // 选择图片返回的相对路径
			encoding: 'base64', // 编码格式
			success: res => { // 成功的回调
				// console.log(res, '返回结果');
				imgbase.value = `data:image/jpeg;base64,${res.data}`;
				// 进行保存上传图片
				saveFmSfz();
			},
			fail: (e) => {
				console.log("图片转换失败");
			}
		})
		// #endif
	}

	function pickok() {
		nextTick(() => {
			pickydata2.value = []
		})
	}

	onLoad(() => {
		userid.value = uni.getStorageSync("userid");
		// console.log('初始化程序加载数据！', userid.value);
		if (isEmpty(userid.value)) {
			uni.redirectTo({
				url: '/pages/auth/auth'
			})
		} else {
			entity.value.wxid = userid.value;
		}

		// 进行数据校验 判断当前学员是否已经绑定过
		loadIsJz();
	})


	const loadIsJz = async () => {
		let param = { "wxid": userid.value }
		const result = await getDetailBywxid(param);
		// console.log(JSON.stringify(result));
		if (!isEmpty(result.id)) {
			uni.setStorageSync("code", "1");
			msg.value.show({ model: 'success',text: '绑定成功' })
			uni.redirectTo({
				url: '/pages/index/my'
			})
		}
	}

	
	function loadXyContent() {
		uni.navigateTo({
			url: `/pages/news/xynews?id=9`
		})
	}

	function allChange(e : any) {
		// console.log(e);
		xyflag.value = e;
	}



	function confirm() {
		// console.log(entity.value.addr);
		if (!xyflag.value) {
			msg.value.show({ model: 'error',text: '请先同意一下协议！' })
			return false;
		}

		if (isEmpty(entity.value.name)) {
			msg.value.show({ model: 'error',text: '姓名不能为空！' })
			return false;
		}
		if (isEmpty(entity.value.cardno)) {
			msg.value.show({ model: 'error',text: '证件号码不能为空！' })
			return false;
		}
		if (!isIdCard(entity.value.cardno)) {
			msg.value.show({ model: 'error',text: '请输入正确的证件号码！' })
			return false;
		}
		// if (isEmpty(entity.value.stuname)) {
		// 	nextTick(() => {
		// 		msg.value.show({ model: 'error', label: "学生姓名不能为空！" })
		// 	})
		// 	return false;
		// }
		if (isEmpty(entity.value.addr)) {
			msg.value.show({ model: 'error',text: '区域地址不能为空！' })
			return false;
		}
		if (isEmpty(entity.value.addrDetail)) {
			msg.value.show({ model: 'error',text: '详细地址不能为空！' })
			return false;
		}
		if (isEmpty(entity.value.phone)) {
			msg.value.show({ model: 'error',text: '联系方式不能为空！' })
			return false;
		}
		if (isEmpty(entity.value.code)) {
			msg.value.show({ model: 'error',text: '验证码不能为空！' })
			return false;
		}



		savebangshou();


		return true;
	}




	const savebangshou = async () => {
		const result = await savejs(entity.value);
		// console.log("返回结果：",JSON.stringify(result));
		if (result.code === "200") {
			uni.setStorageSync("code", "1");
			msg.value.show({ model: 'success',text: '申请成功' })
			uni.redirectTo({
				url: '/pages/index/my'
			})
		} else if (result.code === "400") {
			msg.value.show({ model: 'error',text: result.msg })
		}
	}





	function sendMessage() {
		if(msgFlag.value){
			return false;
		}
		if (isEmpty(entity.value.phone)) {
			msg.value.show({ model: 'error',text: '联系方式不能为空' })
			return false;
		}
		if (!isPhone(entity.value.phone)) {
			msg.value.show({ model: 'error',text: '请填写正确的联系方式' })
			return false;
		}
		loadUserData();
		djsbtn(30);
		return true;
	}

	function djsbtn(seconds : any) {
		msgFlag.value = true;
		let remainingTime = seconds;
		const interval = setInterval(() => {
			remainingTime -= 1;
			if (remainingTime === 0) {
				clearInterval(interval);
				// console.log('Finished'); ysxm
				selab.value = `获取验证码`;
				msgFlag.value = false;
			} else {
				// console.log(remainingTime);
				selab.value = `等待${remainingTime}秒`;
			}
		}, 1000);
	}


	const loadUserData = async () => {
		let param = { "mobile": entity.value.phone };
		const result = await getcode(param);
		// console.log("返回结果：",JSON.stringify(result));
		if (result.code === "200") {
			msg.value.show({ model: 'success',text: '短信发送成功' })
		} else if (result.code === "400") {
			msg.value.show({ model: 'error',text: result.msg })
		}
	}
</script>

<style>

</style>